package com.demo.common.redis.pubsub;

import com.demo.common.redis.RedisProperties;
import com.demo.common.redis.expire.RedisExpiredListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

import javax.annotation.Resource;

/**
 * <p>
 * 消息订阅(pub/sub方式)的基础配置类
 * </p>
 *
 * @author molong
 * @date 2022/6/22
 */
@Configuration
public class BasePubSubConfig {

    @Resource
    private RedisProperties redisProperties;

    /**
     * 定义消息处理容器
     * @param factory 工厂类
     * @return 处理容器
     */
    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory factory){
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(factory);
        if(redisProperties.isKeyEventExpired()){
            container.addMessageListener(new RedisExpiredListener(), new PatternTopic("__keyevent@"+redisProperties.getDatabase()+"__:expired"));
        }
        return container;
    }
}
